package com.webchat.chat.service.impl;

import com.webchat.chat.core.AbstractService;
import com.webchat.chat.core.exception.ServiceException;
import com.webchat.chat.core.tools.ShiroUtil;
import com.webchat.chat.dao.RoleMapper;
import com.webchat.chat.dao.RolePermissionMapper;
import com.webchat.chat.model.Role;
import com.webchat.chat.model.RolePermission;
import com.webchat.chat.service.RolePermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * Created by admin on 2018-06-29.
 */
@Service
@Transactional
public class RolePermissionServiceImpl extends AbstractService<RolePermission> implements RolePermissionService {
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public void updateRoleAndPermission(Role role, String[] permissionIds) {
        String tenantCode = role.getTenantCode();
        String roleName = role.getRoleName();
        Role roleCondition = new Role();
        roleCondition.setTenantCode(tenantCode);
        roleCondition.setRoleName(roleName);
        List<Role> selectRole = roleMapper.select(roleCondition);
        if(selectRole != null && !selectRole.isEmpty()){
            throw new ServiceException("已存在此角色名,请更换角色名重试");
        }
        roleMapper.insertSelective(role);
        for ( String permId:permissionIds) {
            RolePermission rolePermission = new RolePermission(role.getId(), permId);
            rolePermission.setCreatedBy(ShiroUtil.getUserName());
            rolePermission.setCreatedDate(new Date());
            rolePermissionMapper.insert(rolePermission);
        }
    }

    @Override
    public void addRoleAndPermission(Role role, String[] permissionIds) {
        if (StringUtils.isBlank(role.getId())){
            throw new ServiceException("要修改角色id不能为空！！");
        }
        RolePermission rolePerm = new RolePermission();
        rolePerm.setRoleId(role.getId());
        rolePermissionMapper.delete(rolePerm);
        for ( String permId:permissionIds) {
            RolePermission rolePermission = new RolePermission(role.getId(), permId);
            rolePermission.setCreatedBy(ShiroUtil.getUserName());
            rolePermission.setLastModifiedBy(ShiroUtil.getUserName());
            rolePermission.setCreatedDate(new Date());
            rolePermission.setLastModifiedDate(new Date());
            rolePermissionMapper.insert(rolePermission);
        }
    }
}
